import _ from 'lodash';

export default {
  compress(code) {
    let uncompressed = code;

    if (_.isObject(code)) {
      uncompressed = JSON.stringify(code);
    }

    if (uncompressed) return compress(uncompressed);
  }
}

function compress(uncompressed) {
  "use strict";
  // Build the dictionary.
  var i,
    dictionary = {},
    c,
    wc,
    w = "",
    result = [],
    dictSize = Math.pow(2, 16),//Unicode字符最大值加一
    strLength = uncompressed.length;

  for (i = 0; i < strLength; i += 1) {
    c = uncompressed.charAt(i);
    wc = w + c;
    //Do not use dictionary[wc] because javascript arrays 
    //will return values for array['pop'], array['push'] etc
    if (dictionary.hasOwnProperty(wc)) {
      w = wc;
    } else {
      if (w && !dictionary[w]) {
        dictionary[w] = w.charCodeAt(0);
      }

      if (dictionary[w]) {
        result.push(dictionary[w]);
        dictionary[wc] = dictSize++;
      }
      // Add wc to the dictionary.
      w = String(c);
    }
  }

  // Output the code for w.
  if (w !== "") {
    result.push(dictionary[w] || w.charCodeAt(0));
  }
  return result.join(",");
}